package com.ea.eadp.nexus.test.common;

import com.sun.mail.imap.IMAPFolder;
import org.apache.commons.lang.SystemUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.MediaType;

import javax.mail.*;
import javax.mail.internet.MimeUtility;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

/**
 * Created with IntelliJ IDEA.
 * User: jianzhou
 * Date: 9/3/14
 * Time: 3:11 PM
 * To change this template use File | Settings | File Templates.
 */
public class EmailClient {

    private String email = "testreceivea@outlook.com";
    private String emailPwd = "Testrece!bug";
    private static Log log = LogFactory.getLog(EmailClient.class);
    int waitCount = 10;
    int interval = 15;

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getEmailPwd() {
        return emailPwd;
    }

    public void setEmailPwd(String emailPwd) {
        this.emailPwd = emailPwd;
    }

    public String retriveEmail(String domain,String subjectStr) throws Exception {
        int count = 0;
        log.info("retrieving reset password mail");
        IMAPFolder folder = null;
        Store store = null;
        while (count < waitCount) {
            try {
                Properties props = System.getProperties();
                props.setProperty("mail.store.protocol", "imaps");

                Session session = Session.getDefaultInstance(props, null);

                store = session.getStore("imaps");
                store.connect("imap-mail.outlook.com", email, emailPwd);

                folder = (IMAPFolder) store.getFolder("INBOX");

                folder.open(Folder.READ_WRITE);
                Message[] messages = folder.getMessages();
                if (messages.length != 0) {
                    for (int i = messages.length - 1; i >= 0; i--) {
                        Message msg = messages[i];
                        log.info(msg);
                        String from = decodeText(msg.getFrom()[0].toString());
                        String fromEA =domain;

                        String subject = decodeText(msg.getSubject());

                        if (from.contains(fromEA)) {
                            if (subject.contains(subjectStr)) {
                                String body = "";
                                if (msg.isMimeType("multipart/*")) {
                                    Multipart multipart = (Multipart) msg.getContent();
                                    for (int x = 0; x < multipart.getCount(); x++) {
                                        BodyPart bodyPart = multipart.getBodyPart(x);
                                        if (bodyPart.getContentType().toLowerCase().contains(MediaType.TEXT_PLAIN_VALUE.toLowerCase())) {
                                            body = body.concat(bodyPart.getContent().toString() + SystemUtils.LINE_SEPARATOR);
                                        }
                                    }
                                } else {
                                    body = (String) msg.getContent();
                                }
                                return body;
                            }
                        }
                    }
                }
            } finally {
                folder.close(true);
                store.close();
            }
            log.info("wait " + interval + " seconds for reset password mail...");
            Thread.sleep(interval * 1000);
            count++;
        }
        throw new Exception("retrieve mail timeout");
    }
    public String retriveEmail(String subjectStr) throws Exception {
       return retriveEmail("@em.ea.com",subjectStr);
    }


    private String decodeText(String text)
            throws UnsupportedEncodingException {
        if (text == null)
            return null;
        if (text.startsWith("=?GB") || text.startsWith("=?gb"))
            text = MimeUtility.decodeText(text);
        else
            text = new String(text.getBytes("ISO8859_1"));
        return text;
    }


    public void cleanUpEmail() throws Exception {
        log.info("clean up email");
        IMAPFolder folder = null;
        Store store = null;
        Flags.Flag flag = Flags.Flag.DELETED;
        try {
            Properties props = System.getProperties();
            props.setProperty("mail.imap.port", "993");
            props.setProperty("mail.store.protocol", "imaps");
            props.setProperty("proxySet", "true");

            Session session = Session.getDefaultInstance(props, null);

            store = session.getStore("imaps");
            store.connect("imap-mail.outlook.com", email, emailPwd);

            folder = (IMAPFolder) store.getFolder("INBOX");

            folder.open(Folder.READ_WRITE);
            Message[] messages = folder.getMessages();
            if (messages.length == 0)
                return;

            for (Message msg : messages) {
                msg.setFlag(flag, true);
            }
        } finally {
            if (folder.isOpen()){
            folder.close(true);
            }
            store.close();
        }
    }
}
